#include <QtGui>
#include "helper.h"
#include <stdio.h>
#include <math.h>

//! [0]
Helper::Helper()
{
    QLinearGradient gradient(QPointF(50, -20), QPointF(80, 20));
    gradient.setColorAt(0.0, Qt::white);
    gradient.setColorAt(1.0, QColor(0xa6, 0xce, 0x39));

    background = QBrush(QColor(255, 255, 255));
    circleBrush = QBrush(Qt::green);
    circlePen = QPen(Qt::green);
    circlePen.setWidth(1);
    textPen = QPen(Qt::white);
    textFont.setPixelSize(50);
}
//! [0]

//! [1]
void Helper::paint(QPainter *painter, QPaintEvent *event, int elapsed)
{
    painter->fillRect(event->rect(), background);
    painter->translate(100, 100);
//! [1]

//! [2]
    painter->save();
    //painter->setPen(circlePen);
    //painter->setBrush(circleBrush);
    //painter->rotate(elapsed * 0.030);

    qreal r = elapsed/1000.0;
    //int n = 30;
    for (int i = 0; i < BioUnitList->count(); i++)
    {
        BioUnit* b = BioUnitList->at(i);
        if(b->biomass <= 0)
        {
            BioUnitList->removeAt(i);
        }
        b->x += (0.03)*b->Vx;
        b->y += (0.03)*b->Vy;
        b->biomass -= fabs(b->Vx)/200.0 + fabs(b->Vy)/200.0;
        b->biomass += b->green*(0.03)/10.0;
        if(b->biomass >= 250)
        {
            BioUnitList->insert(i,new BioUnit(b));
        }
        //if(b->currentTask != 0 && b->currentTask->mode != Task::Stop)
        //    painter->drawLine(b->x,b->y,b->currentTask->x,b->currentTask->y);
        painter->setBrush(QBrush(QColor(0, 255.0*b->green/100.0, 0,(120 - b->invisible)%100)));
        painter->setPen(QPen(QColor(0, 255.0*b->green/100.0, 0,(120 - b->invisible)%100)));
        //painter->fillRect(QRectF(b->x-5, b->y-5,10, 10),QBrush(QColor(0, 255.0*b->green/100.0, 0,(120 - b->invisible)%100)));
        painter->drawEllipse(QRectF(b->x-b->size, b->y-b->size,(b->size)*2, (b->size)*2));
        //painter->drawText(b->x, b->y + 10, QString("a%1 g%2 mass%3").arg(b->agressive).arg(b->green).arg(b->biomass));
        painter->drawText(b->x, b->y + 10, QString("%1").arg((int)(b->biomass)));
        b->DoThink(0.03);
    }
    painter->restore();
//! [2]

//! [3]
    painter->setPen(textPen);
    painter->setFont(textFont);
}
//! [3]
